<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拷贝</title>
</head>
<body>
    <h1>深拷贝与浅拷贝</h1>
<script>
    /**
     * 深拷贝[默认基本类型都是深拷贝]
     */
    //1.Object.assign({},"要拷贝的对象")【如果有引用类型就是浅拷贝】
    let obj1={
        name:"碰磕",
        age:20
    }
    let newobj=Object.assign({},obj1);
    console.log(newobj);
    newobj.age="19";
    console.log(newobj,obj1);
    //2.JSON.parse(JSON.stringify())
    let obj2={
        name:"碰磕",
        age:20,
        hobby:{
            hobby1:"学习"
        },
        hello:function(){
            console.log("hello");
        }
    }
    let newobj2=JSON.parse(JSON.stringify(obj2));
    console.log('拷贝后',newobj2)
    newobj2.hobby.hobby1="吃饭";
    console.log('原对象',obj2);
    console.log("更新后的对象",newobj2);

    //手写一个深拷贝
    function allcopy(obj){
        if(typeof obj=="object"){
            let dist;
            if(obj instanceof Array){
                dist=new Array();
            }else{
                dist=new Object();
            }
            for (const item in obj) {
                if(obj.hasOwnProperty(item)){
                    dist[item]=allcopy(obj[item])
                }
            }
            return dist;
        }else if(typeof obj=="function"){
            dist=function(){    //拷贝参数和函数体
                return obj.apply(this,arguments)
            }
        }else if(obj instanceof Date){
            dist=new Date(obj)
        }
        return obj;
    }
    let mynewobj=allcopy(obj2)
    mynewobj.hobby.hobby1='打游戏';
    console.log("手写的深拷贝：",mynewobj,obj2)

    /**
     * 浅拷贝
     */
    let qobj={
        xingming:"碰磕",
        nianling:66,
        aihao:{
            num1:"学习",
            num2:"Music"
        }
    }
    //方式一...解构
    let qnewobj={...qobj};
    qnewobj.aihao.num1="aaa";
    console.log("拷贝的",qnewobj,"原来",qobj)//被改变了所以是浅拷贝
    //方式二:for...in
    let qnewobj1={};
    for (const key in qobj) {
        qnewobj1[key]=qobj[key]
    }
    qnewobj1.aihao.num1="6666";
    console.log("拷贝的",qnewobj1,"原来",qobj)//被改变了所以是浅拷贝

</script>
</body>
</html>